package cn.gok.common.config;

import cn.gok.common.enums.ResultEnum;
import cn.gok.common.resp.Result;
import cn.gok.utils.ResultUtil;
import com.alibaba.fastjson.JSON;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 描述：客户端的登录拦截
 * 用户中心的相关操作都会拦截
 *
 * @author shikundai
 * @date 2020/12/10
 * @time 11:30
 */
@WebFilter(urlPatterns = {"/client/person/*"})
public class ClientLoginAop implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获取登录信息
        Object login = req.getSession().getAttribute("customerId");
        //有登陆直接放行
        if (login != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            /*
             * 判断是同步请求还是异步请求
             * 不同的请求返回数据不同
             * */
            Object obj = req.getHeader("x-requested-with");
//            同步请求
            if (obj == null) {
                //跳转到登录界面
                resp.sendRedirect(req.getServletContext().getContextPath() + "/client/home/login.html");
            } else {
                //异步请求
                //返回错误信息
                Result result = ResultUtil.info(ResultEnum.SYSTEM_UNKNOWN_ERROR.getCode(), "用户未登录", "");
                resp.getWriter().println(JSON.toJSONString(result));
                resp.getWriter().flush();
            }
        }

    }

    @Override
    public void destroy() {

    }
}
